/* *****************************************************************************
*
*	danizone.ch
*
*	Developer:		mda010
*	Creation date:	May 6, 2012 9:29:11 PM
*	
*	Project name:	HomegrownCuisine
*	File name:		JPADao.java
*
*	Copyrights (C) 2012 @danizone.ch
*
*   This program is free software; you can redistribute it and/or modify
*	it under the terms of the GNU General Public License as published by
*	the Free Software Foundation; either version 2 of the License, or
*	(at your option) any later version.
*
*	This program is distributed in the hope that it will be useful,
*	but WITHOUT ANY WARRANTY; without even the implied warranty of
*	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*	GNU General Public License for more details.
*
*	Change history:	[developer]; [date];[reason for change]
*
*					mda010; May 6, 2012; created
*
***************************************************************************** */
package ch.zhaw.hgc.daos.base;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

/**
 * Implementation note goes here!
 */
@Transactional(readOnly=true, noRollbackFor=NoResultException.class)
public abstract class JPADao<T, K> implements IDao<T, K>{
	
	protected EntityManager entityManager;

	protected final Class<? extends T> javaType;
	protected final String entityName;
	
	public JPADao(final Class<? extends T> javaType){
		this.javaType = javaType;
		this.entityName = this.javaType.getSimpleName();
	}
	
	@PersistenceContext
	public void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;
	}

	/* (non-Javadoc)
	 * @see com.wartsila.daos.IDao#findById(java.lang.Object)
	 */
	@Override
	public T findById(Object key){
		return entityManager.find(javaType, key);
	}

	/* (non-Javadoc)
	 * @see com.wartsila.daos.IDao#findAll()
	 */
	@SuppressWarnings("unchecked")
	@Override	
	public List<T> findAll(){
		return entityManager.createQuery("select from " + entityName).getResultList();
	}

	/* (non-Javadoc)
	 * @see com.wartsila.daos.IDao#craete(java.lang.Object)
	 */
	@Override	
	@Transactional
	public T create(T t){
		entityManager.persist(t);
		entityManager.flush();
		return t;
	}

	/* (non-Javadoc)
	 * @see com.wartsila.daos.IDao#update(java.lang.Object)
	 */
	@Override
	@Transactional
	public T update(T t){
		t = entityManager.merge(t);
		entityManager.flush();
		return t;
	}

	/* (non-Javadoc)
	 * @see com.wartsila.utils.db.IDao#remove(java.lang.Object)
	 */
	@Override
	@Transactional
	public void remove(T t){
		entityManager.remove(entityManager.merge(t));
		entityManager.flush();
	}
}